package org.darchitect.nn.som.ui;

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Point2D;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class SOMColorGrid extends JPanel {

	private static final long serialVersionUID = 1L;
	private double w[][][];
	private JComboBox componentA;
	private JComboBox componentB;
	private JComboBox componentC;
	JToolBar bar;
	private ColorPanel cPanel;
	private Point2D selectedPoint;
	
	public SOMColorGrid(double w[][][]) {
		this.w = w;
		setUpUI();
	}
	
	private void setUpUI() {
		double d[][][] = selectComponents(0, 1, 2);
		cPanel = new ColorPanel(d);
		
		bar = new JToolBar();
		bar.setFloatable(false);
		
		Vector<Integer> vv = new Vector<Integer>();
		for (int i = 0; i < w[0][0].length; i++)
			vv.add(i+1);
		componentA = new JComboBox(vv);
		componentA.setSelectedIndex(0);
		componentB = new JComboBox(vv);
		componentB.setSelectedIndex(1);
		componentC = new JComboBox(vv);
		componentC.setSelectedIndex(2);
		componentA.addItemListener(itemListener);
		componentB.addItemListener(itemListener);
		componentC.addItemListener(itemListener);
		
		bar.add(componentA);
		bar.add(componentB);
		bar.add(componentC);
		
		setLayout(new BorderLayout());
		add(bar, BorderLayout.NORTH);
		add(cPanel, BorderLayout.CENTER);
	}
	
	public void selectNodeAt(Point2D p) {
		if (selectedPoint != null)
			cPanel.removeSelectedPoint(selectedPoint);
		p.setLocation(p.getX(), p.getY() - bar.getHeight());
		cPanel.addSelectedPoint(p);
		selectedPoint = p;
		cPanel.repaint();
	}
	
	private double[][][] selectComponents(int a, int b, int c) {
		double d[][][] = new double[w.length][w[0].length][3];
		for (int i = 0; i < d.length; i++)
			for (int j = 0; j < d[i].length; j++) {
				d[i][j][0] = w[i][j][a];
				d[i][j][1] = w[i][j][b];
				d[i][j][2] = w[i][j][c];
			}
		return d;
	}
	
	private ItemListener itemListener = new ItemListener() {
		@Override
		public void itemStateChanged(ItemEvent e) {
			int a = componentA.getSelectedIndex(); 
			int b = componentB.getSelectedIndex();
			int c = componentC.getSelectedIndex();
			cPanel.setWeights(selectComponents(a, b, c));
			cPanel.repaint();
		}
	};

	public Point2D getNodeCoordinates(Point2D clickedPoint) {
		int width = cPanel.getCellWidth();
		Point2D p = new Point((int)(clickedPoint.getX() / width), (int)(clickedPoint.getY() / width));
		return p;
	}
	
}
